import React, {useContext, useMemo, useState} from "react";
import Drawer from "@src/components/Drawer";
import "./index.scss"
import {formatTime} from "@src/utils/date.ts"
import {useAudioPlayer} from "@src/store/music.ts";
import LivingIcon from "@src/components/LivingIcon"
import {Swiper, SwiperSlide} from "swiper/react";
import type {Swiper as SwiperRef} from 'swiper';
import InputIcon from "@src/components/inputIcon";
import SearchIcon from "@src/assets/search.svg?react"
import {useRequest} from "ahooks";
import {search, songsType} from "@src/services/music.ts";
import {ThemeContext} from "../../_context/index.ts"
import toast from 'react-hot-toast';
import {addChatroomSong, CurrentSong} from "@src/services/chatRoom.ts";
import {socketCreate} from "@src/store/socket"


type SongsListProps = {
    isOpen: boolean; // 当前的显示状态
    setIsOpen: React.Dispatch<React.SetStateAction<boolean>>; // 用于改变状态的函数
};

//歌单列表
const SongsList: React.FC<SongsListProps> = ({isOpen, setIsOpen}) => {
    const {currentSongList, switchSongLogic, locationState} = useContext(ThemeContext);
    const {song} = useAudioPlayer()
    //轮播图控制器
    const [controlledSwiper, setControlledSwiper] = useState<SwiperRef>();

    const [activeIndex, setActiveIndex] = useState(0);
    //搜索文本
    const [searchInput, setSearchInput] = useState("");
    //筛选文本
    const [screenInput, setScreenInput] = useState("");
    const currentSongListScreen = useMemo(() => {
        const currentSongListScreen: CurrentSong[] | undefined = currentSongList?.filter(item => item.name.includes(screenInput))
        return currentSongListScreen
    }, [currentSongList, screenInput])
    //搜索歌曲
    const searchApi = useRequest(search, {manual: true})
    const addChatroomSongApi = useRequest(addChatroomSong, {manual: true})
    //搜索
    const searchClick = () => {
        if (searchInput.trim() !== "") {
            searchApi.runAsync(searchInput, 30).then((data) => {
                console.log(data);
            })
            setSearchInput("")
        }
    }
    const {socket} = socketCreate();
    //添加歌曲
    const AddSong = (item: songsType) => {
        const currentSong: CurrentSong = {
            id: item.id,
            name: item.name,
            time: item.dt,
            author: item.ar[0].name,
            picUrl: item.al.picUrl,
        }
        if (currentSongList?.some((s) => s.id.toString() == item.id.toString())) {
            toast("这首歌以及在列表中了哦~", {icon: "😢"})
        } else {
            addChatroomSongApi.run(locationState.roomID, currentSong)
            socket.emit("group:hint_message", {
                groupId: locationState.roomID.toString(), content: {
                    message: "添加歌曲",
                    currentSong: currentSong
                }
            })
        }
    }
    const nextSong = (item: songsType) => {
        const currentSong: CurrentSong = {
            id: item.id,
            name: item.name,
            time: item.dt,
            author: item.ar[0].name,
            picUrl: item.al.picUrl,
        }
        if (currentSongList?.some((s) => s.id.toString() == item.id.toString())) {
            socket.emit("group:hint_message", {
                groupId: locationState.roomID.toString(), content: {
                    message: "立即播放",
                    currentSong: currentSong
                }
            })
        } else {
            addChatroomSongApi.run(locationState.roomID, currentSong)
            socket.emit("group:hint_message", {
                groupId: locationState.roomID.toString(), content: {
                    message: "立即播放",
                    currentSong: currentSong
                }
            })
        }
    }


    return <Drawer position="bottom" height="50%" isOpen={isOpen} setIsOpen={setIsOpen}>
        <div className="ChatSongsList">
            <div className="song-head">
                <h4 className={activeIndex == 0 ? "active" : ""}
                    onClick={() => controlledSwiper?.slideTo(0)}>歌曲列表</h4>
                <h4 className={activeIndex == 1 ? "active" : ""}
                    onClick={() => controlledSwiper?.slideTo(1)}>添加歌曲</h4>
            </div>

            <Swiper onSwiper={setControlledSwiper} onSlideChange={(swiper) => setActiveIndex(swiper.activeIndex)}>
                <SwiperSlide>
                    <div className="song-list-div">
                        <InputIcon
                            onChange={(e) => setScreenInput(e.target.value)}
                            type="search"
                            Icon={<SearchIcon></SearchIcon>}
                            placeholder="筛选歌曲">
                        </InputIcon>

                        <ul className="song-ul">
                            {currentSongListScreen?.map((item) =>
                                <li key={item.id}
                                    onClick={() => {
                                        if (song.id != item.id) {
                                            switchSongLogic(item.id)
                                        } else {
                                            toast("当前播放的就是这首歌哦~", {icon: "🫠"})
                                        }
                                    }}>
                                    <div className={"song-li " + (song.id == item.id ? "activity" : "")}>
                                        <div className="picUrl">
                                            <img src={item.picUrl} alt=""/>
                                        </div>
                                        <div>
                                            <h4 className="text-overflow-1">{item.name}</h4>
                                            <p className="text-overflow-1">{item.author}</p>
                                            <div>
                                                <div>
                                                    {song.id == item.id && <LivingIcon></LivingIcon>}
                                                </div>
                                                {formatTime(item.time)}
                                            </div>
                                        </div>
                                    </div>

                                </li>
                            )}
                        </ul>
                    </div>
                </SwiperSlide>

                <SwiperSlide>
                    <div className="search-div">
                        <InputIcon
                            onKeyDown={(e) => {
                                if (e.key === 'Enter') {
                                    searchClick()
                                }
                            }}
                            type="search"
                            onChange={(e) => setSearchInput(e.target.value)}
                            value={searchInput}
                            Icon={<SearchIcon></SearchIcon>}
                            placeholder="搜索你想添加的歌">
                        </InputIcon>

                        <ul className="song-ul">
                            {searchApi.data?.result?.songs?.map(item => (
                                <li key={item.id}>
                                    <div className="song-li">
                                        <div className="picUrl">
                                            <img src={item.al.picUrl} alt=""/>
                                        </div>
                                        <div>
                                            <h4 className="text-overflow-1">{item.name}</h4>
                                            <p className="text-overflow-1">{item.ar[0].name}</p>
                                            <div>
                                                <div>
                                                    {song.id == item.id && <LivingIcon></LivingIcon>}
                                                </div>
                                                {formatTime(item.dt)}
                                            </div>
                                        </div>
                                    </div>
                                    <div className="song-ul-btn">
                                        <button className="z-button" onClick={() => AddSong(item)}>加入播放列表</button>
                                        <button className="z-button" onClick={() => nextSong(item)}>立刻播放</button>
                                    </div>
                                </li>
                            ))}
                        </ul>

                    </div>
                </SwiperSlide>

            </Swiper>
        </div>


    </Drawer>
}
export default SongsList;